package com.mrx.xfriendship.converter;

import com.mrx.xfriendship.model.dto.PostDTO;
import com.mrx.xfriendship.model.po.PostPO;
import com.mrx.xfriendship.model.vo.PostVO;
import org.apache.commons.lang3.math.NumberUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingConstants;

/**
 * @author Mr.X
 * @since 2023-01-15 07:55
 */
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING,
        uses = {CommentConverter.class, OtherConverter.class}
)
public interface PostConverter extends IConverter<PostPO, PostDTO> {

    @Override
    @Mapping(target = "tag", expression = "java( po.getTag().getName() )")
    @Mapping(target = "publishTime", source = "createTime")
    @Mapping(target = "lastReplier", source = "lastComment")
    @Mapping(target = "title", expression = "java( po.getTitle() )")
    @Mapping(target = "content", expression = "java( po.getContent() )")
    PostDTO toDTO(PostPO po);

    @Mapping(target = "title", expression = "java( vo.getTitle() )")
    @Mapping(target = "content", expression = "java( vo.getContent() )")
    PostPO toPO(PostVO vo);

    default PostPO toPO(PostDTO dto) {
        if (dto == null) return null;
        PostPO po = new PostPO();
        po.setId(dto.getId());
        // 如果 tag 不是 数字, 那就不管
        if (NumberUtils.isDigits(dto.getTag())) {
            po.setTagId(Integer.parseInt(dto.getTag()));
        }
        po.setTitle(dto.getTitle());
        po.setContent(dto.getContent());
        return po;
    }

}
